# ========================================
# FlorisBoard → CocoKeyboard 批量重命名脚本
# ========================================

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "FlorisBoard → CocoKeyboard 重命名工具" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

$projectRoot = $PSScriptRoot
Set-Location $projectRoot

# 定义替换规则（按大小写匹配）
$replacements = @(
    # 包名和命名空间
    @{ Pattern = 'dev\.patrickgold\.florisboard'; Replacement = 'com.coco.cocokeyboard' },
    @{ Pattern = 'dev/patrickgold/florisboard'; Replacement = 'com/coco/cocokeyboard' },
    @{ Pattern = 'dev\\patrickgold\\florisboard'; Replacement = 'com\coco\cocokeyboard' },
    
    # 类名和变量名（精确匹配大小写）
    @{ Pattern = 'FlorisBoard'; Replacement = 'CocoKeyboard' },
    @{ Pattern = 'Floris([A-Z])'; Replacement = 'Coco$1' },  # FlorisXxx → CocoXxx
    @{ Pattern = 'florisboard'; Replacement = 'cocokeyboard' },
    @{ Pattern = 'floris_'; Replacement = 'coco_' },  # floris_app_name → coco_app_name
    @{ Pattern = 'FLORISBOARD'; Replacement = 'COCOKEYBOARD' },
    
    # 特殊情况
    @{ Pattern = 'florisBoard'; Replacement = 'cocoKeyboard' },
    @{ Pattern = 'FLADDONS'; Replacement = 'COCOADDONS' },
    @{ Pattern = 'fladdons'; Replacement = 'cocoaddons' }
)

# 需要处理的文件扩展名
$fileExtensions = @('*.kt', '*.kts', '*.xml', '*.gradle', '*.properties', '*.json', '*.md', '*.txt', '*.sh', '*.bat', '*.py', '*.toml', '*.pro')

# 排除的目录
$excludeDirs = @('.git', '.gradle', '.idea', '.kotlin', 'build', 'node_modules')

Write-Host "[1/4] 扫描需要修改的文件..." -ForegroundColor Yellow

# 获取所有需要处理的文件
$allFiles = @()
foreach ($ext in $fileExtensions) {
    $files = Get-ChildItem -Path $projectRoot -Filter $ext -Recurse -File | 
        Where-Object { 
            $excluded = $false
            foreach ($dir in $excludeDirs) {
                if ($_.FullName -like "*\$dir\*") {
                    $excluded = $true
                    break
                }
            }
            -not $excluded
        }
    $allFiles += $files
}

Write-Host "   找到 $($allFiles.Count) 个文件需要处理" -ForegroundColor Green
Write-Host ""

Write-Host "[2/4] 执行文件内容替换..." -ForegroundColor Yellow

$modifiedCount = 0
$totalReplacements = 0

foreach ($file in $allFiles) {
    try {
        $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8 -ErrorAction Stop
        $originalContent = $content
        $fileModified = $false
        $fileReplacements = 0
        
        # 应用所有替换规则
        foreach ($rule in $replacements) {
            $pattern = $rule.Pattern
            $replacement = $rule.Replacement
            
            # 计算替换次数
            $matches = [regex]::Matches($content, $pattern)
            if ($matches.Count -gt 0) {
                $content = $content -replace $pattern, $replacement
                $fileReplacements += $matches.Count
                $fileModified = $true
            }
        }
        
        # 如果文件被修改，写回文件
        if ($fileModified) {
            Set-Content -Path $file.FullName -Value $content -Encoding UTF8 -NoNewline
            $modifiedCount++
            $totalReplacements += $fileReplacements
            
            $relativePath = $file.FullName.Substring($projectRoot.Length + 1)
            Write-Host "   ✓ $relativePath ($fileReplacements 处替换)" -ForegroundColor Gray
        }
    }
    catch {
        Write-Host "   ✗ 处理失败: $($file.Name) - $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "   共修改 $modifiedCount 个文件，执行了 $totalReplacements 处替换" -ForegroundColor Green
Write-Host ""

Write-Host "[3/4] 检测需要重命名的文件和目录..." -ForegroundColor Yellow

# 查找需要重命名的文件（文件名包含 floris 或 Floris）
$filesToRename = Get-ChildItem -Path $projectRoot -Recurse -File |
    Where-Object { 
        $_.Name -match 'floris|Floris' -and 
        $excludeDirs -notcontains $_.Directory.Name
    } |
    Sort-Object { $_.FullName.Length } -Descending  # 从最深的路径开始

# 查找需要重命名的目录
$dirsToRename = Get-ChildItem -Path $projectRoot -Recurse -Directory |
    Where-Object { 
        $_.Name -match 'floris|Floris' -and 
        $excludeDirs -notcontains $_.Name
    } |
    Sort-Object { $_.FullName.Length } -Descending  # 从最深的路径开始

Write-Host "   找到 $($filesToRename.Count) 个文件和 $($dirsToRename.Count) 个目录需要重命名" -ForegroundColor Green
Write-Host ""

Write-Host "[4/4] 执行文件和目录重命名..." -ForegroundColor Yellow

# 重命名文件
$renamedFilesCount = 0
foreach ($file in $filesToRename) {
    try {
        $newName = $file.Name
        $newName = $newName -replace 'FlorisBoard', 'CocoKeyboard'
        $newName = $newName -replace 'Floris([A-Z])', 'Coco$1'
        $newName = $newName -replace 'florisboard', 'cocokeyboard'
        $newName = $newName -replace 'floris_', 'coco_'
        $newName = $newName -replace 'floris', 'coco'
        
        if ($newName -ne $file.Name) {
            $newPath = Join-Path $file.Directory.FullName $newName
            
            if (Test-Path $newPath) {
                Write-Host "   ⚠ 目标文件已存在，跳过: $newName" -ForegroundColor DarkYellow
            } else {
                Move-Item -Path $file.FullName -Destination $newPath -Force
                $renamedFilesCount++
                
                $relativePath = $file.FullName.Substring($projectRoot.Length + 1)
                Write-Host "   ✓ $relativePath → $newName" -ForegroundColor Gray
            }
        }
    }
    catch {
        Write-Host "   ✗ 重命名失败: $($file.Name) - $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 重命名目录
$renamedDirsCount = 0
foreach ($dir in $dirsToRename) {
    try {
        $newName = $dir.Name
        $newName = $newName -replace 'florisboard', 'cocokeyboard'
        $newName = $newName -replace 'floris', 'coco'
        
        if ($newName -ne $dir.Name) {
            $newPath = Join-Path $dir.Parent.FullName $newName
            
            if (Test-Path $newPath) {
                Write-Host "   ⚠ 目标目录已存在，跳过: $newName" -ForegroundColor DarkYellow
            } else {
                Move-Item -Path $dir.FullName -Destination $newPath -Force
                $renamedDirsCount++
                
                $relativePath = $dir.FullName.Substring($projectRoot.Length + 1)
                Write-Host "   ✓ $relativePath → $newName" -ForegroundColor Gray
            }
        }
    }
    catch {
        Write-Host "   ✗ 重命名失败: $($dir.Name) - $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "   共重命名 $renamedFilesCount 个文件和 $renamedDirsCount 个目录" -ForegroundColor Green
Write-Host ""

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "重命名完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "📊 统计信息：" -ForegroundColor Cyan
Write-Host "  • 修改文件数：$modifiedCount" -ForegroundColor White
Write-Host "  • 替换次数：$totalReplacements" -ForegroundColor White
Write-Host "  • 重命名文件：$renamedFilesCount" -ForegroundColor White
Write-Host "  • 重命名目录：$renamedDirsCount" -ForegroundColor White
Write-Host ""
Write-Host "⚠ 重要提示：" -ForegroundColor Yellow
Write-Host "  1. 请执行 'git status' 查看所有变更" -ForegroundColor White
Write-Host "  2. 建议执行 './gradlew clean' 清理构建缓存" -ForegroundColor White
Write-Host "  3. 重新打开 Android Studio 同步项目" -ForegroundColor White
Write-Host "  4. 检查是否有编译错误" -ForegroundColor White
Write-Host ""

pause

